<!-- 3d地图组件 -->
<template>
  <div id="cesiumContainer"></div>
</template>
<script setup>
import * as Cesium from 'cesium';
import { onMounted } from 'vue';
onMounted(() => {
  // 设置令牌
  Cesium.Ion.defaultAccessToken = '自己的令牌'
  // 自定义地图
  const cesium = new Cesium.ArcGisMapServerImageryProvider({
    url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer'
    // url:'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
  })
  // 异步加载世界地形
  const addWorldTerrainAsync = async (viewer) => {
    try {
      const terrainProvider = await Cesium.createWorldTerrainAsync({
        requestWaterMask: true, // 请求水体效果
        requestVertexNormals: true // 请求地形照明数据
      });
      viewer.terrainProvider = terrainProvider;
    } catch (error) {
      console.log(`Failed to add world terrain: ${error}`);
    }
  };
  const viewer = new Cesium.Viewer('cesiumContainer', {
    baseLayerPicker: false, // 是否显示BaseLayerPicker控件
    infoBox: false, // 禁用InfoBox
    // imageryProvider: cesium, // 设置图像提供
  });
  addWorldTerrainAsync(viewer);
  // 配置视角
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.4, 39.9, 5000), // 设置初始坐标(x,y,z)
    // 设置方向属性:方向、俯视、仰视
    orientation: {
      // 设置度数(Cesium.Math.toRadians(90))或0~1(0.60)之间的值
      heading: Cesium.Math.toRadians(90),//设置顺时针转90度
      pitch: Cesium.Math.toRadians(-90), // 负数俯视整数仰视
      roll: 0,//以世界坐标获取相机的正确方向。
    }
  })

  const city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
    url: Cesium.IonResource.fromAssetId(3845) // 北京3D建筑资产ID
  }));
  // 定义3d样式
  var heightStyle = new Cesium.Cesium3DTileStyle({
    color: {
      //条件判断具体的颜色
      conditions: [
        ['${height} >= 300', 'rgba(45,0,75,0.5)'],
        ['${height} >= 200', 'rgba(102,71,151,0.5)'],
        ['${height} >= 100', 'rgba(170,162,204,0.5)'],
        ['${height} >= 25', 'rgba(224,226,238,0.5)'],
        ['${height} >= 10', 'rgba(248,176,87,0.5)'],
        ['${height} >= 5', 'rgba(198,106,11,0.5)'],
        ['true', 'rgba(125,59,8,0.5)'],
      ]
    }
  })
  city.style = heightStyle


  // 加载完成后调整视角
  // city.readyPromise.then(function () {
  //   const center = Cesium.Cartesian3.fromDegrees(116.3998, 39.9394, 1000); // 鸟巢

  //   viewer.camera.flyTo({
  //     destination: center,
  //     orientation: {
  //       heading: Cesium.Math.toRadians(0.0),
  //       pitch: Cesium.Math.toRadians(-30.0),
  //       roll: 0.0
  //     },
  //     duration: 3
  //   });
  // }).catch(function (error) {
  //   console.error('3D模型加载失败:', error);
  // });

})
</script>
<style scoped>
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  margin: 0;
}
</style>